#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{

    ui->setupUi(this);
    mm = new MyTimer;
    QTimer *timer = new QTimer(this);
    connect(ui->pushButton_start,SIGNAL(clicked(bool)),this, SLOT(myTimer_Start()));  //开始信号
    connect(ui->pushButton_stop,SIGNAL(clicked(bool)),this, SLOT(myTimer_Stop()));    //暂停信号
    connect(ui->pushButton_clear,SIGNAL(clicked(bool)),this, SLOT(myTimer_Clear()));   //清除信号
    connect(mm->myTimers,SIGNAL(timeout()),this, SLOT(showTimeLast()));
    connect(mm->myTimers,SIGNAL(timeout()), this, SLOT(timeAdd()));
    connect(timer, SIGNAL(timeout()), this, SLOT(showTime()));
    ui->lcdNumber->setSegmentStyle(QLCDNumber::Flat);
    ui->lcdNumber->display(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    ui->label_time->setText(QDateTime::currentDateTime().toString("hh:mm:ss"));
    timer->setInterval(1000);
    timer->start(); //计时器开始运行
}

Widget::~Widget()
{
    delete ui;
}

void Widget::myTimer_Start()
{
    if(!startPushed){
        mm->intMyTime_last = 0;
        ui->lcdNumber_start->display(QTime::currentTime().toString("hh:mm:ss"));
        mm->myTimers->start();
        ui->lcdNumber_end->display(0);
        startPushed = true;
        ui->pushButton_start->setText("Go On");
    }
    else if(startPushed && stopPushed){
        mm->myTimers->start();
        stopPushed = false; //将stop按钮弹起，恢复初始可操作状态
        ui->lcdNumber_end->display(0);
        qDebug()<<"intMyTime_last->:"<<mm->intMyTime_last;
    }
    else{
        NULL;
    }
}

void Widget::myTimer_Stop()
{
    if(startPushed)ui->lcdNumber_end->display(QDateTime::currentDateTime().toString("hh:mm:ss"));
    if(!stopPushed && startPushed){
        mm->myTimers->stop();
        stopPushed = true;
    }
    else{
        NULL;
    }
}

void Widget::myTimer_Clear()
{
    mm->myTimers->stop();
    startPushed = false;
    ui->pushButton_start->setText("Start");
    stopPushed = false;
    ui->lcdNumber_start->display(0);
    ui->lcdNumber_last->display(0);
    ui->lcdNumber_end->display(0);
    mm->intMyTime_last = 0;
}

void Widget::timeAdd()
{
    if(startPushed){
        mm->intMyTime_last += 47;
    }
}

void Widget::showTime()
{
    //获取系统时间
    QDateTime dateTime = QDateTime::currentDateTime();
    // 按格式显示的内容
    ui->lcdNumber->display(dateTime.toString("yyyy-MM-dd hh:mm:ss"));
}

void Widget::showTimeLast()
{
    int t = mm->intMyTime_last;
    int t_m = t/60000;  //分钟数
    int t_s = (t - t_m*60000) / 1000;   //秒数
    int t_ms = (t - t_m*60000 - t_s*1000);  //毫秒数
    //timelast格式一定要与QTime::currentTime()一毛一样，不然无法转换成QTime类型
    QString timeLast = QString("%1:%2:%3.%4").arg(t_m,2,10,QChar('0')).arg(t_m,2,10,QChar('0')).arg(t_s,2,10,QChar('0')).arg(t_ms,3,10,QChar('0'));
    QTime s = QTime::fromString(timeLast, Qt::TextDate);
    ui->lcdNumber_last->display(s.toString("mm:ss.zzz"));
}
